// 将时间字符串转换成为长整形数字

const week = ["/u65e5", "/u4e00", "/u4e8c", "/u4e09", "/u56db", "/u4e94", "/u516d"]; // 一、二、三、四、五、六、七
const weekPrefix = {
	"1": "/u5468", // 周
	"2": "/u661f/u671f" // 星期
};
/**
 * 进行日期格式的转换
 * @param date
 * @param format
 * @returns {void|string|XML|*}
 */
const format = (exports.format = function (date, formatStr) {
	let map = {
		M: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		m: date.getMinutes(),
		s: date.getSeconds(),
		q: Math.floor((date.getMonth() + 3) / 3),
		S: date.getMilliseconds()
	};

	formatStr = formatStr.replace(/([yMdhmsqSW])+/g, function (all, t) {
		let v = map[t];
		if (v !== undefined) {
			if (all.length > 1) {
				v = "0" + v;
				v = v.substr(v.length - 2);
			}
			return v;
		} else if (t === "y") {
			let i = 4 - all.length;
			return i <= 0 ? date.getFullYear() + "" : (date.getFullYear() + "").substr(i);
		} else if (t === "W") {
			return (weekPrefix[all.length + ""] || "") + week[date.getDay()];
		}
		return all;
	});

	return formatStr;
});

/**
 * 将时间字符串转换成14位的数字
 * @param date
 * @returns {string}
 */
exports.toLong = function (date) {
	const arr = [];

	arr.push(
		date.getFullYear(),
		"0" + (date.getMonth() + 1),
		"0" + date.getDate(),
		"0" + date.getHours(),
		"0" + date.getMinutes(),
		"0" + date.getSeconds()
	);
	for (let l = arr.length; l-- && l > 0;) {
		arr[l] = arr[l].substr(arr[l].length - 2);
	}
	return parseInt(arr.join(""), 10);
};

exports.strToLong = function (dateStr) {
	const date = new Date(Date.parse(dateStr));

	return exports.toLong(date);
};

exports.longToStr = function (long, formatStr) {
	const dateStr = long + "";

	return format(
		new Date(
			`${dateStr.substr(0, 4)}-${dateStr.substr(4, 2)}-${dateStr.substr(6, 2)} ${dateStr.substr(
				8,
				2
			)}:${dateStr.substr(10, 2)}:${dateStr.substr(12, 2)}`
		),
		formatStr
	);
};
